import { g6Debounce } from 'glasssix-utils-ts';
export default (listRequest: ListRequestFunction) => {
	const state = reactive({
		pageSize: 10,
		pageIndex: 1,
		listData: [],
		searchObj: {},
		total: 0,
		isEnd: false
	});

	const getList = async (isReset = false, isload = false): Promise<void> => {
		try {
			state.isEnd = false;
			if (isReset) {
				state.pageIndex = 1;
				state.pageSize = 10;
			}
			const res = await listRequest({
				pageIndex: state.pageIndex,
				pageSize: state.pageSize,
				...state.searchObj
			});
			if (res.status === 0) {
				if (!isload) {
					state.listData = res.result.list;
					state.total = res.result.total;
				} else {
					state.listData = state.listData.concat(res.result.list);
					if (res.result.list.length < state.pageSize) {
						state.isEnd = true;
					}
				}
			}
		} catch (e) {
			console.log('error', e);
		}
	};

	const loadList = () => {
		if (!state.isEnd) {
			state.pageIndex++;
			getList(false, true);
		}
	};

	//   const throttledFunc = debounce((data: any) => {
	//     Object.assign(state.searchObj, { ...data });
	//     getList(true);
	//   }, 500);

	const searchList = (data: any) => {
		g6Debounce(getList(true), 500);
	};

	return {
		state,
		searchList,
		getList,
		loadList
	};
};
